package com.adolph.netty.nettydemo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * 〈功能概述〉<br>
 *
 * @author: wangxiangjun
 * @date: 2020-10-09 9:29
 */

public class NettyServerHandlerLast extends ChannelInboundHandlerAdapter {

    /**
     * 读取信息
     * @Author wangxiangjun
     * @Date 9:34 2020-10-09
     * @param ctx 上下文信息，含有管道、通道、地址
     * @param msg
     * @return void
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("NettyServerHandlerLast======3");
        ByteBuf byteBuf = (ByteBuf) msg;
        String tempStr = byteBuf.toString(CharsetUtil.UTF_8);
        System.out.println("NettyServerHandlerNext接收消息：====="+tempStr);
        tempStr =tempStr + "==3==";
        byteBuf.writeBytes(tempStr.getBytes(CharsetUtil.UTF_8));
        ctx.writeAndFlush(msg);
    }

    //数据读取完毕
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//        ctx.flush();
        //数据写入缓存并刷新
//        ctx.writeAndFlush(Unpooled.copiedBuffer("服务端发送消息",CharsetUtil.UTF_8));
    }

    //异常处理，关闭通道
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("NettyServerHandlerLast===========channelInactive");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("NettyServerHandlerLast===========channelActive");
    }
}
